package com.sai.jsai.module.system.service.impl;

import com.sai.jsai.common.starter.mybatisplus.service.impl.BaseServiceImpl;
import com.sai.jsai.module.system.api.dto.SysMenuTreeDTO;
import com.sai.jsai.module.system.convert.SysMenuConvert;
import com.sai.jsai.module.system.dal.entity.SysMenu;
import com.sai.jsai.module.system.dal.mapper.SysMenuMapper;
import com.sai.jsai.module.system.service.SysMenuService;
import com.sai.jsai.module.system.service.SysRoleMenuService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author jisai
 * @version 0.0.1
 * @Description 系统菜单 服务实现类
 * @createTime 2024/09/24
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    /**
     * 根菜单父ID
     */
    private final static Long ROOT_MENU_PARENT_ID = 0L;

    @Resource
    SysRoleMenuService sysRoleMenuService;

    /**
     * 按角色ID获取菜单树
     *
     * @param sysRoleIds 角色ID列表
     * @return 菜单树
     */
    @Override
    public List<SysMenuTreeDTO> getMenuTreeByRoleIds(List<Long> sysRoleIds) {
        List<Long> menuIds = sysRoleMenuService.getMenuIdsByRoleIds(sysRoleIds);
        List<SysMenu> sysMenus = this.listByIds(menuIds);
        return buildMenuTree(SysMenuConvert.INSTANCE.convertToMenuTreeList(sysMenus) , ROOT_MENU_PARENT_ID);
    }

    /**
     * 构建菜单树
     *
     * @param sysMenuTreeList 系统菜单列表
     * @param parentId 父节点ID
     * @return 菜单树
     */
    private List<SysMenuTreeDTO> buildMenuTree(List<SysMenuTreeDTO> sysMenuTreeList, Long parentId) {
        List<SysMenuTreeDTO> parentMenuTreeList = sysMenuTreeList.stream().filter(sysMenu -> sysMenu.getParentId().equals(parentId)).toList();
        for (SysMenuTreeDTO sysMenuTree : sysMenuTreeList) {
            if (sysMenuTree.getParentId().equals(parentId)) {
                sysMenuTree.setChildren(buildMenuTree(sysMenuTreeList, sysMenuTree.getId()));
            }
        }
        return parentMenuTreeList;
    }

}
